﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Memcached.ClientLibrary;

namespace cmsservice.Common.Memcached
{
    public class News2CacheTools : IMemcachedCache
    {
        static string cacheName = Guid.NewGuid().ToString();
        static News2CacheTools()
        {
            String[] serverlist = System.Configuration.ConfigurationManager.AppSettings["news2Memcache"].Split(',','|');
            SockIOPool pool = SockIOPool.GetInstance(cacheName);
            pool.SetServers(serverlist);
            pool.Initialize();
        }

        public object GetClient()
        {
            MemcachedClient mc = new MemcachedClient();
            mc.PoolName = cacheName;
            mc.EnableCompression = false;
            return mc;
        }
 
        public T Get<T>(string key)
        {
            MemcachedClient cache = (MemcachedClient)GetClient();
            return (T)cache.Get(key);
        }


        public void Add(string key, object obj, int hours, int minutes, int seconds)
        {
            MemcachedClient cache = (MemcachedClient)GetClient();
            if (!cache.Add(key, obj, DateTime.Now.Add(new TimeSpan(hours, minutes, seconds))))
            { 
                cache.Set(key, obj, DateTime.Now.Add(new TimeSpan(hours, minutes, seconds)));
            }
        }

        public void Remove(string key)
        {
            MemcachedClient cache = (MemcachedClient)GetClient();
            cache.Delete(key);
        }

        public void FlushAll()
        {
            throw new NotImplementedException();
        }
    }
}
